package com.crazymaker.agent.demo.bytebuddy;

import java.lang.reflect.Method;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;

public class CostTimeTracer {


    static ThreadLocal<Stack<SimpleSpan>> spanStack = ThreadLocal.withInitial(() -> new Stack<>());

    public static CostTimeTracer newTracer() {
        return new CostTimeTracer();
    }

    public static SimpleSpan newSpan(Method method) {
        SimpleSpan simpleSpan = new SimpleSpan();
        simpleSpan.method = method;
        return simpleSpan;
    }

    public static SimpleSpan currentSpan() {

        return spanStack.get().peek();
    }


    public static class SimpleSpan {

        int spanId;
        static final AtomicInteger count = new AtomicInteger(0);

        public Method method;
        private long startTime;

        public void start() {
            System.out.println("-- start a method span:" + this);
            spanId=count.incrementAndGet();

            spanStack.get().push(this);
            startTime = System.currentTimeMillis();

        }

        public void end() {
            SimpleSpan target = spanStack.get().pop();
            if (!target.equals(this)) {
                throw new RuntimeException("弹出的次序有误");
            }
            System.out.println(this + "-- cost:" + (System.currentTimeMillis() - this.startTime));
        }

        @Override
        public String toString() {
            return "spanId:"+spanId+" method :"+method.getName();
        }
    }
}